package cc.bable.alipay.starter.autoconfigure;

import cc.bable.alipay.starter.properties.AlipayProperties;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Configuration
@EnableConfigurationProperties({AlipayProperties.class})
public class AlipayAutoConfiguration {
	private static final String ERROR_MSG_APPID_NULL = "Alipay application's appid cann't be null";
	private static final String ERROR_MSG_PRIVATE_KEY_NULL = "Alipay app's private key cann't be null";
	private static final String ERROR_MSG_ALIPAY_PUBLIC_KEY_NULL = "Alipay's public key cann't be null";
	public static final String GATEWAY = "https://openapi.alipay.com/gateway.do";

	public AlipayAutoConfiguration() {
	}

	@Bean
	public AlipayClient alipayClient(AlipayProperties properties) {
		String appId = Objects.requireNonNull(properties.getAppId(), ERROR_MSG_APPID_NULL);
		String privateKey = Objects.requireNonNull(properties.getPrivateKey(), ERROR_MSG_PRIVATE_KEY_NULL);
		String alipayPublicKey = Objects.requireNonNull(properties.getAlipayPublicKey(), ERROR_MSG_ALIPAY_PUBLIC_KEY_NULL);
		String signType = AlipayConstants.SIGN_TYPE_RSA.equals(properties.getSignType()) ? AlipayConstants.SIGN_TYPE_RSA : AlipayConstants.SIGN_TYPE_RSA2;
		return new DefaultAlipayClient(GATEWAY, appId, privateKey, AlipayConstants.FORMAT_JSON, AlipayConstants.CHARSET_UTF8, alipayPublicKey, signType);
	}
}
